﻿using System.Windows;
using System.Windows.Input;
using System.Windows.Interactivity;
using Infragistics.Controls.Grids;

namespace UI.Core.Behaviors
{
    public class XamGridDoubleClickBehavior : Behavior<XamGrid>
    {
        public bool DisableDetach { get; set; }

        private XamGrid Grid
        {
            get { return AssociatedObject as XamGrid; }
        }

        public ICommand DoubleClick
        {
            get { return (ICommand)GetValue(DoubleClickProperty); }
            set { SetValue(DoubleClickProperty, value); }
        }

        public static readonly DependencyProperty DoubleClickProperty = DependencyProperty.Register("DoubleClick", typeof(ICommand), typeof(XamGridDoubleClickBehavior), null);

        protected override void OnAttached()
        {
            base.OnAttached();
            Grid.MouseDoubleClick += GridMouseDoubleClick;
            Grid.Unloaded += Grid_Unloaded;
        }

        void Grid_Unloaded(object sender, RoutedEventArgs e)
        {
            Detach();
        }

        protected override void OnDetaching()
        {

            if (DisableDetach)
            {
                Grid.MouseDoubleClick -= GridMouseDoubleClick;
                Grid.Unloaded -= Grid_Unloaded;
            }

            base.OnDetaching();
        }

        void GridMouseDoubleClick(object sender, MouseButtonEventArgs e)
        {

            var fe = (FrameworkElement)e.OriginalSource;
            DoubleClick.Execute(fe.DataContext);
        }

    }
}
